<?php
require_once 'include/inc.config.php';
require_once WACT_ROOT . '/db/db.inc.php';
require_once APP_ROOT.'model/common/utils.php';
require_once APP_ROOT.'model/common/session.php';
require_once APP_ROOT.'model/common/date.php';
require_once APP_ROOT.'model/common/parameters.php';
require_once APP_ROOT.'model/common/site.php';
require_once APP_ROOT.'model/common/statteams.php';



class Score {


    function insertScore(&$data) {
    	$site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
    	$enabled = $data->get('enabled');
    	if (!$enabled) $data->set('enabled',0);

    	$tz =& new MyTimeZone();
        $data->set('date_added', gmdate("Y-m-d H:i", $tz->timeNowLocal() ) );

        $Record =& DBC::NewRecord($data);
        $ret = $Record->insertId('sport_stat_scores',
            array('site_id','date_added', 'seasonYear', 'team1ID', 'team2ID', 'score1', 'score2', 'enabled','gameName','gameDate'), 'scoreID');

		// update team statistics
		$team1ID = $data->get('team1ID');
    	$team2ID = $data->get('team2ID');
        if ($team1ID) StatTeam::calculateTeamStats($team1ID);
        if ($team2ID) StatTeam::calculateTeamStats($team2ID);

		return $ret;

    }



    function &getRecord($id) {
        return DBC::FindRecord("
        SELECT S.*, T1.teamName as teamName1, T2.teamName as teamName2,
        D1.divisionName as divisionName1, D2.divisionName as divisionName2,
        T1.wins as wins1, T1.losses as losses1, T1.ties as ties1, T1.pct as pct1,
        T2.wins as wins2, T2.losses as losses2, T2.ties as ties2, T2.pct as pct2
        FROM sport_stat_scores S
        left outer join sport_stat_teams T1 on S.team1ID = T1.teamID
        left outer join sport_stat_teams T2 on S.team2ID = T2.teamID
     	left outer join sport_stat_divisions D1 on T1.divisionID = D1.divisionID
        left outer join sport_stat_divisions D2 on T2.divisionID = D2.divisionID
        WHERE S.scoreID  = ". DBC::makeLiteral($id));
    }

    function updateScore($id, &$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);

    	$enabled = $data->get('enabled');
    	if (!$enabled) $data->set('enabled',0);

        $Record =& DBC::NewRecord($data);
        $Record->update('sport_stat_scores',
            array('site_id','seasonYear', 'team1ID', 'team2ID', 'score1', 'score2', 'enabled','gameName','gameDate'),
            "scoreID=". DBC::makeLiteral($id));

        // update team statistics
		$team1ID = $data->get('team1ID');
    	$team2ID = $data->get('team2ID');
        if ($team1ID) StatTeam::calculateTeamStats($team1ID);
        if ($team2ID) StatTeam::calculateTeamStats($team2ID);
    }

    function resetAllStats() {
    	DBC::execute("update sport_stat_scores set enabled=0");
		// reset all stats
		DBC::execute("update sport_stat_teams set wins=0, losses=0, ties=0, pct=0");
    }

	function deleteAllDisabledStats() {
    	DBC::execute("delete from sport_stat_scores where enabled=0");
    }




    function denyScore($score_id) {
        $data = new DataSpace();
        $data->set('enabled',0);



    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_stat_scores', array('enabled'),
            "scoreID=". DBC::makeLiteral($score_id));

        $rec =& Score::getRecord($score_id);
        // update team statistics
		$team1ID = $rec->get('team1ID');
    	$team2ID = $rec->get('team2ID');
        if ($team1ID) StatTeam::calculateTeamStats($team1ID);
        if ($team2ID) StatTeam::calculateTeamStats($team2ID);
    }

    function publishScore($score_id) {
        $data = new DataSpace();
        $data->set('enabled',1);



    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_stat_scores',
            array('enabled'), "scoreID=". DBC::makeLiteral($score_id));

        $rec =& Score::getRecord($score_id);
        // update team statistics
		$team1ID = $rec->get('team1ID');
    	$team2ID = $rec->get('team2ID');
        if ($team1ID) StatTeam::calculateTeamStats($team1ID);
        if ($team2ID) StatTeam::calculateTeamStats($team2ID);
    }



	function delete($score_id) {
        $rec =& Score::getRecord($score_id);

        DBC::execute("DELETE FROM sport_stat_scores WHERE scoreID=". DBC::makeLiteral($score_id));

        // update team statistics
		$team1ID = $rec->get('team1ID');
    	$team2ID = $rec->get('team2ID');
        if ($team1ID) StatTeam::calculateTeamStats($team1ID);
        if ($team2ID) StatTeam::calculateTeamStats($team2ID);
    }

    function &getScoresList(&$Pager, &$request, &$responseModel,$options=null, $onlynew=false) {
        $site_id = Site::getSiteID();
     	//restore filter from session
     	Session::loadResponseModel($responseModel,'filter.scores');
     	$sql = "
     	SELECT S.*, T1.teamName as teamName1, T2.teamName as teamName2,
        D1.divisionName as divisionName1, D2.divisionName as divisionName2,
        T1.wins as wins1, T1.losses as losses1, T1.ties as ties1,  T1.pct as pct1,
        T2.wins as wins2, T2.losses as losses2, T2.ties as ties2, T2.pct as pct2,
        L.leagueName
        FROM sport_stat_scores S
        left outer join sport_stat_teams T1 on S.team1ID = T1.teamID
        left outer join sport_stat_teams T2 on S.team2ID = T2.teamID
     	left outer join sport_stat_divisions D1 on T1.divisionID = D1.divisionID
        left outer join sport_stat_divisions D2 on T2.divisionID = D2.divisionID
        left outer join sport_stat_leagues L
     	on D1.leagueID = L.leagueID
     	";

     	if($options==null){
     		if ($onlynew) {
                $sql.=" where 1=1 and (S.enabled=0 or S.enabled is null)
                and S.site_id = ".DBC::makeLiteral($site_id)." ".Score::getScoreFilter($request, $responseModel)."
     		 	order by S.date_added desc ";
     		} else {
     			$sql.=" where 1=1
                and S.site_id = ".DBC::makeLiteral($site_id)." ".Score::getScoreFilter($request, $responseModel)."
     		 	order by ".Score::getScoreOrder($request, $responseModel);
     		}
            //print $sql;
        	return DBC::NewPagedRecordSet($sql, $Pager);
     	}else{
     		$sql.=" where 1=1
             and S.site_id = ".DBC::makeLiteral($site_id);
     		$sql.=" order by S.date_added desc ";
     		error_log("[SQL:]$sql");
     		//print $sql;
     		return DBC::NewPagedRecordSet($sql, $Pager);
     	}
     }

     function getScoreFilter(&$request,&$responseModel) {
      	$where = '';
      	$filter_score_id = $responseModel->get('filter_score_id');
        $score_id = $responseModel->get('score_id');
      	if ($filter_score_id)  $where .= ' and S.scoreID = '.DBC::makeLiteral($score_id);

        $filter_title = $responseModel->get('filter_gameName');
        $title = $responseModel->get('gameName');
        if ($filter_title)  $where .= ' and S.gameName like '.DBC::makeLiteral('%'.$title.'%').'  ';

        $filter_team = $responseModel->get('filter_teamID');
        $team = $responseModel->get('teamID');
        if ($filter_team)  $where .= ' and S.team1ID = '.
        DBC::makeLiteral($team).
        ' or S.team2ID ='.DBC::makeLiteral($team);

        $filter_season = $responseModel->get('filter_seasonYear');
        $season = $responseModel->get('seasonYear');
        if ($filter_season)  $where .= ' and S.seasonYear = '.
        DBC::makeLiteral($season);

        $filter_division_id = $responseModel->get('filter_division_id');
        $division_id = $responseModel->get('division_id');
      	if ($filter_division_id)  $where .= ' and (D1.divisionID = '.DBC::makeLiteral($division_id).
      	' or D2.divisionID = '.DBC::makeLiteral($division_id).')';

        $filter_start_date = $responseModel->get('start_date_filter');
        $start_day = $responseModel->get('start_day');
        $start_month = $responseModel->get('start_month');
        $start_year = $responseModel->get('start_year');
        $start_date = gmmktime(0, 0, 0, $start_month, $start_day, $start_year);
        $tz =& new MyTimeZone();
        $start_date = $tz->timeLocal( $start_date );
        if ($filter_start_date) $where .= " and S.gameDate>='".gmdate("Y.m.d",$start_date)."'";

        $filter_end_date = $responseModel->get('end_date_filter');
        $end_day = $responseModel->get('end_day');
        $end_month = $responseModel->get('end_month');
        $end_year = $responseModel->get('end_year');
        $end_date = gmmktime(0, 0, 0, $end_month, $end_day, $end_year);
        $end_date = $tz->timeLocal( $end_date );
        if ($filter_end_date) $where .= " and S.gameDate<='".gmdate("Y.m.d",$end_date)."'";


        return $where;
      }

      function getScoreOrder(&$request,&$responseModel) {
      	$sortby = ' S.date_added desc';
      	$sortby = $responseModel->get('sort');
      	if ($sortby) return $sortby;
      	else return ' S.date_added desc';
      }


      function &getNewScoreList(&$Pager, &$request, &$responseModel) {
      	return Score::getScoreList($Pager, $request, $responseModel,null,true);
      }



     function &getPublicScores($teamID) {
        $site_id = Site::getSiteID();

     	$sql = "SELECT T1.teamName as teamName1, T2.teamName as teamName2,
        D1.divisionName as divisionName1, D2.divisionName as divisionName2,
        T1.wins as wins1, T1.losses as losses1, T1.ties as ties1, T1.pct as pct1,
        T2.wins as wins2, T2.losses as losses2, T2.ties as ties2, T2.pct as pct2,
        S.*, L.leagueName
        FROM sport_stat_scores S
        inner join sport_stat_teams T1 on S.team1ID = T1.teamID
        inner join sport_stat_teams T2 on S.team2ID = T2.teamID
     	inner join sport_stat_divisions D1 on T1.divisionID = D1.divisionID
        inner join sport_stat_divisions D2 on T2.divisionID = D2.divisionID
        left outer join sport_stat_leagues L
     	on D1.leagueID = L.leagueID
        where S.enabled = 1 ";
     	if($teamID) $sql.=" and (S.team1ID = ".DBC::makeLiteral($teamID).
     	" or S.team2ID = ".DBC::makeLiteral($teamID).") ";
     	$sql.=" and S.site_id = ".DBC::makeLiteral($site_id);
        $sql.=" order by S.date_added desc ";
     	//print  $sql;
        $rs =& DBC::NewRecordSet($sql);
        return $rs;

     }

    function getTeamWins($teamID) {
        $site_id = Site::getSiteID();
    	return DBC::getOneValue("Select count(*) from sport_stat_scores
    	where  site_id = ".DBC::makeLiteral($site_id).
    	" and enabled = 1 and
    	(score1 > score2 and team1ID = ".DBC::makeLiteral($teamID).")".
    	" or  (score1 < score2 and team2ID = ".DBC::makeLiteral($teamID).")");
    }

    function getTeamLosses($teamID) {
        $site_id = Site::getSiteID();
    	return DBC::getOneValue("Select count(*) from sport_stat_scores
    	where  site_id = ".DBC::makeLiteral($site_id).
    	" and enabled = 1 and
    	(score1 < score2 and team1ID = ".DBC::makeLiteral($teamID).")".
    	" or  (score1 > score2 and team2ID = ".DBC::makeLiteral($teamID).")");
    }

    function getTeamTies($teamID) {
        $site_id = Site::getSiteID();
    	return DBC::getOneValue("Select count(*) from sport_stat_scores
    	where  site_id = ".DBC::makeLiteral($site_id).
    	" and enabled = 1 and
    	(score1 = score2 and team1ID = ".DBC::makeLiteral($teamID).")".
    	" or  (score1 = score2 and team2ID = ".DBC::makeLiteral($teamID).")");
    }









}

?>
